/*
 * Copyright 2010 Biz-e (info@biz-e.nl)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.site.server.dao;

import java.util.ArrayList;
import java.util.List;

import nl.biz_e.appengine.lib.server.objectify.AbstractBaseDao;
import nl.biz_e.site.server.models.NewsItemText;
import nl.biz_e.site.shared.models.NewsItem;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

/**
 * Offers database access methods for {@link NewsItem} and {@link NewsItemText}
 * objects
 * 
 * @author Joost A. Bloemsma
 */
public class NewsItemDao extends AbstractBaseDao<NewsItem> {
	static {
		ObjectifyService.register(NewsItem.class);
		ObjectifyService.register(NewsItemText.class);
	}
	
	/**
	 * Constructs a new NewsItemDao instance
	 */
	public NewsItemDao() {
		super(NewsItem.class);
	}
	
	/**
	 * @param count
	 * @return List
	 */
	public List<NewsItem> getLast(int count) {
		Query<NewsItem> q = qry();
		q.order("-seqNr");
		q.limit(count);
		List<NewsItem> items = new ArrayList<NewsItem>();
		for (NewsItem item : q) {
			items.add(item);
		}
		return items;
	}
	
	/**
	 * returns the highest sequence number currently in use on the datastore
	 * 
	 * @return long
	 */
	public long getLastSeqNr() {
		List<NewsItem> list = getLast(1);
		if (list.size() == 0) {
			return 0;
		} else {
			return list.get(0).getSeqNr();
		}
	}
	
	/**
	 * @param item
	 * @return The full text
	 */
	public String getFullText(NewsItem item) {
		Key<NewsItem> itemKey = new Key<NewsItem>(NewsItem.class, item.getId());
		NewsItemText text = ofy()
				.get(new Key<NewsItemText>(NewsItemText.class, itemKey.toString()));
		return text.getText();
	}
	
	/**
	 * @param item
	 * @param text
	 */
	public void saveFullText(NewsItem item, String text) {
		ofy().put(new NewsItemText(item, text));
	}
}
